//
//  QQShare.m
//  yuikemall
//
//  Created by yuike5 yuike5 on 12-6-14.
//  Copyright (c) 2012年 yuike. All rights reserved.
//

#import "QQShare.h"
//#import "SourceXmlModel.h"
//#import "ParametersHeader.h"
//#import ".h"
#import "Toast+UIView.h"

@implementation QQShare
#define GlobalSettings QQShare

static NSString* g_qqshare_appid = nil;
+(void) setDefaultAppid:(NSString*)appid {
    [g_qqshare_appid release];
    g_qqshare_appid = [appid copy];
}


+(NSString*) getGlobalValueByKey:(NSString*)key defaultValue:(NSString*)defaultValue {
    key = [NSString stringWithFormat:@"GlobalValueByKey%@", key];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString* value = [defaults valueForKey:key];
    if (!value) return defaultValue;
    return value;
}

+(void) setGlobalValue:(NSString*)value forKey:(NSString*)key 
{
    key = [NSString stringWithFormat:@"GlobalValueByKey%@", key];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:value forKey:key];
    [defaults synchronize];
}




- (void)dealloc {
    _tencentOAuth.sessionDelegate = nil;
	[_tencentOAuth release];
    [super dealloc];
}

- (id) init {
    self = [super init];
    if (self) {
        NSString* appid = g_qqshare_appid;
        _tencentOAuth = [[TencentOAuth alloc] initWithAppId:appid
                                                andDelegate:self];
        _tencentOAuth.redirectURI = @"www.qq.com";
        [self reloadAuthInfo];
    }
    return self;
}


-(NSArray*)emotions
{
    return [NSArray array];
}

//static NSString* kGraphBaseURL = @"https://graph.qq.com/oauth2.0/";
//static NSString* kRedirectURL = @"www.qq.com";
//static NSString* kRestserverBaseURL = @"https://graph.qq.com/";
-(NSArray*)urlStringsforCookies {
    return [NSArray arrayWithObjects:
            @"https://graph.qq.com/oauth2.0/",
            @"https://graph.qq.com/",
            @"http://www.qq.com",
            nil];
}

-(void) addShare:(id<WeiboCommitDelegate>)delegate_ content:(NSString*)content 
           title:(NSString*)title_ url:(NSString*)url summary:(NSString*)summary
        imageurl:(NSString*)imageurl {
    [self setOnetimeDelegate: delegate_];
    content = [content stringByReplacingOccurrencesOfString:self.rootNick withString:self.nick];
    while ([content rangeOfString:@"  "].location != NSNotFound) // 规整
        content = [[content stringByReplacingOccurrencesOfString:@"  " withString:@" "] 
                   stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    // onClickAddShare -- add Share...
    NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
								   title_, @"title",
								   url, @"url",
								   content, @"comment",
								   summary, @"summary",
                                   @"json", @"format",
								   @"5", @"source",//通过 IPAD
                                   @"4", @"type",//表示网页
                                   @"http://www.yuike.com/", @"site",
                                   @"0", @"nswb",
								   nil];	

    if (imageurl != nil && imageurl.length>0) 
        [params setValue:imageurl forKey:@"images"];
	[_tencentOAuth addShareWithParams:params];
}

- (void)addShareResponse:(APIResponse*) response {
	if (response==nil || response.retCode != URLREQUEST_SUCCEED) {
        [self.getWeiboCommitDelegate commitCallbackError:self reason:response.errorMsg];
	} else {
        [self.getWeiboCommitDelegate commitCallback:self];
	}	
}


-(void) getUserInfo:(id<WeiboGetUserInfoDelegate>)delegate_
{
    [self setOnetimeDelegate: delegate_];
    [_tencentOAuth getUserInfo];
}

/**
 * Called when the get_user_info has response.
 */
/*!
 @method     getUserInfoResponse:
 @discussion Called when the get_user_info has response.
 @param      response response
 */
- (void)getUserInfoResponse:(APIResponse*) response {
    if (response==nil || response.retCode != URLREQUEST_SUCCEED)
        [self.getWeiboGetUserInfoDelegate getUserInfoError:self];
    else {
        NSString* nick = [response.jsonResponse valueForKey:@"nickname"];
        NSString* domain = @"QQShare";
        WeiboUserNode* user = [[[WeiboUserNode alloc] initWithQQ: response.jsonResponse] autorelease];
        [self.getWeiboGetUserInfoDelegate getUserInfoCallback:self nick:nick domain:domain user:user];
    }
}


-(NSString*) title
{
    return @"QQ分享";
}

-(int) theSnsId
{
    return SNS_ID_QQ_SHARE;
}

-(NSString*) _protected_nick 
{
    return @"@yuiketech"; // 没有 @nick
}

-(void) cancelAll {
//    _tencentOAuth c 暂时为空。。。
}


-(BOOL) isAuthorized
{
    [self reloadAuthInfo];
    return _tencentOAuth.isSessionValid;
}

-(void) auth:(id<WeiboAuthDelegate>)delegate_
{
    self.authDelegate = delegate_;    
    UIWebView* authview = [self.authDelegate weiboAuthview];
    self.authDelegateBackup = authview.delegate;    
    
    NSArray* _permissions =  [NSArray arrayWithObjects:
                              @"get_user_info",@"add_share", // @"add_topic",
                              //@"list_album", @"upload_pic", @"add_album",
                              nil];
    [_tencentOAuth authorize:_permissions inSafari:NO webview:authview];
}


#define QQShare_accessToken     @"QQShare_accessToken_v1"
#define QQShare_expirationDate  @"QQShare_expirationDate_v1"
#define QQShare_openId          @"QQShare_openId_v1"
#define QQShare_appId           @"QQShare_appId_v1"
+ (NSString *) date2string:(NSDate *) _date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *strDate = [dateFormatter stringFromDate:_date];
    NSLog(@"%@", strDate);
    [dateFormatter release];
    return strDate;
}

+ (NSDate *) string2date:(NSString *) _string
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:_string];
    NSLog(@"%@", date);
    [dateFormatter release];
    
    return date;
}

-(void) reloadAuthInfo // @Override
{
    NSString* _accessToken = [GlobalSettings getGlobalValueByKey:QQShare_accessToken defaultValue:nil];    
    NSDate* _expirationDate = [GlobalSettings string2date:[GlobalSettings getGlobalValueByKey:QQShare_expirationDate defaultValue:nil]];
    NSString* _openId = [GlobalSettings getGlobalValueByKey:QQShare_openId defaultValue:nil];  
    NSString* _appId = [GlobalSettings getGlobalValueByKey:QQShare_appId defaultValue:nil];
    // yeah...
    if (_appId && [_tencentOAuth.appId compare:_appId] == 0) {
        _tencentOAuth.accessToken = _accessToken;
        _tencentOAuth.expirationDate = _expirationDate;
        _tencentOAuth.openId = _openId;
    } else {        
        _tencentOAuth.accessToken = nil;
        _tencentOAuth.expirationDate = nil;
        _tencentOAuth.openId = nil;
    }
}
-(BOOL) saveAuthInfo
{
    if (_tencentOAuth.appId==nil || _tencentOAuth.accessToken==nil || 
        _tencentOAuth.expirationDate==nil || _tencentOAuth.openId==nil)
        return false;    
    [GlobalSettings setGlobalValue:_tencentOAuth.appId forKey:QQShare_appId];
    [GlobalSettings setGlobalValue:_tencentOAuth.accessToken forKey:QQShare_accessToken];
    [GlobalSettings setGlobalValue:[GlobalSettings date2string: _tencentOAuth.expirationDate] forKey:QQShare_expirationDate];
    [GlobalSettings setGlobalValue:_tencentOAuth.openId forKey:QQShare_openId];
    return true;
}

-(void) _protected_signOut
{
    [GlobalSettings setGlobalValue:_tencentOAuth.appId forKey:QQShare_appId];
    [GlobalSettings setGlobalValue:nil forKey:QQShare_accessToken];
    [GlobalSettings setGlobalValue:nil forKey:QQShare_expirationDate];
    [GlobalSettings setGlobalValue:nil forKey:QQShare_openId];
    // backup code... log out....
    _tencentOAuth.accessToken = nil;
    _tencentOAuth.expirationDate = nil;
    _tencentOAuth.openId = nil;
}

















// 登陆回调。。。。
/**
 * Called when the user successfully logged in.
 */
- (void)tencentDidLogin {
	// 登录成功       
    if ([self saveAuthInfo]) {
        UIWebView* authview = [self.authDelegate weiboAuthview];
        authview.delegate = self.authDelegateBackup;
        [self.authDelegate authCallback];
    }
}

/**
 * Called when the user dismissed the dialog without logging in.
 */
- (void)tencentDidNotLogin:(BOOL)cancelled {
}

/**
 * Called when the notNewWork.
 */
-(void)tencentDidNotNetWork
{
	UIWindow* window = [UIApplication sharedApplication].keyWindow;
	if (!window) {
		window = [[UIApplication sharedApplication].windows objectAtIndex:0];
	}
    UIView* view = [window.subviews lastObject];
    [view makeToast: @"无网络连接，请设置网络"];
}
@end
